/**
 * 
 */
package wpmp.security.mgr.service;

import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import wcommons.lang.DateUtils;
import wcommons.lang.NumberUtils;
import wcommons.lang.quickbean.Message;
import wpmp.security.mgr.base.BaseService;
import wpmp.security.mgr.dao.CodeDao;
import wpmp.security.mgr.dao.CodeSortDao;
import wpmp.security.mgr.entity.CodeSort;

/**
 * @author Wayne.Wang<5waynewang@gmail.com>
 * @since 3:44:22 PM Mar 18, 2013
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class CodeSortService extends BaseService {

	// private static final Logger LOG =
	// LoggerFactory.getLogger(CodeSortService.class);

	// 需要更新的字段
	private static final String[] UPDATE_PROPERTIES = { "name", "type", "memo" };

	private static final String SQL_EXISTS_CODE = "EXISTS(SELECT 1 FROM sys_code WHERE sort_id={alias}.id AND id=?)";

	private CodeSortDao dao;

	private CodeDao codeDao;

	public CodeSortDao getDao() {
		return dao;
	}

	@Autowired
	public void setDao(CodeSortDao dao) {
		this.dao = dao;
	}

	@Autowired
	public void setCodeDao(CodeDao codeDao) {
		this.codeDao = codeDao;
	}

	public CodeSort get(Long id) {
		CodeSort entity = dao.get(id);
		if (entity == null) {
			return entity;
		}
		CodeSort result = new CodeSort();
		BeanUtils.copyProperties(entity, result);
		return result;
	}

	public CodeSort getByCodeId(Long codeId) {
		return dao.queryForObject(Restrictions.sqlRestriction(SQL_EXISTS_CODE, codeId,
				StandardBasicTypes.LONG));
	}

	private Criteria getCriteria(CodeSort entity) {
		Criteria criteria = dao.createCriteria();
		if (StringUtils.isNotBlank(entity.getName())) {
			criteria.add(Restrictions.like("name", entity.getName(), MatchMode.ANYWHERE));
		}
		return criteria;
	}

	public int count(CodeSort entity) {
		return dao.queryForInt(getCriteria(entity));
	}

	public List<CodeSort> list(CodeSort entity) {
		return dao.queryForList(getCriteria(entity).addOrder(Order.desc("updateTime")));
	}

	public Message validateType(CodeSort entity) {
		Criteria criteria = dao.createCriteria(Restrictions.eq("type", entity.getType()));
		if (NumberUtils.gtZero(entity.getId())) {
			criteria.add(Restrictions.ne("id", entity.getId()));
		}
		if (dao.queryForInt(criteria) > 0) {
			return Message.getErrorMessage("已存在编码[" + entity.getType() + "]");
		}
		return Message.getDefaultMessage();
	}

	public Message insert(CodeSort entity) {
		Message message = validateType(entity);
		if (message.notpass()) {
			return message;
		}

		Timestamp currentTime = new Timestamp(System.currentTimeMillis());
		entity.setCreateTime(currentTime);
		entity.setCreateUser(entity.getSysLoginName());
		entity.setUpdateTime(currentTime);
		entity.setUpdateUser(entity.getSysLoginName());
		dao.save(entity);

		return message;
	}

	public Message update(CodeSort entity) {
		Message message = validateType(entity);
		if (message.notpass()) {
			return message;
		}

		CodeSort result = dao.get(entity.getId());

		wcommons.beanutils.BeanUtils.copyProperties(result, entity, UPDATE_PROPERTIES, false);
		result.setUpdateTime(DateUtils.newTimestamp());
		result.setUpdateUser(entity.getSysLoginName());
		dao.save(result);

		return message;
	}

	public Message delete(Long[] ids) throws Exception {
		if (ArrayUtils.isEmpty(ids)) {
			return Message.getErrorMessage("请选择您要删除的记录");
		}

		List<CodeSort> entities = new LinkedList<CodeSort>();
		for (Long id : ids) {
			CodeSort entity = dao.get(id);
			if (entity == null) {
				continue;
			}
			entities.add(entity);
		}
		if (CollectionUtils.isNotEmpty(entities)) {
			dao.delete(entities);
		}

		// 删除子类
		codeDao.deleteBySortId(ids);

		return Message.getDefaultMessage();
	}
}
